import { reactive, toRefs, computed, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '../utils/http'

export function usePageEdit(options = {}) {
  const route = useRoute()
  const router = useRouter()

  const pageForm = ref()

  const state = reactive({
    // 面包屑
    breadcrumb: route.meta.breadcrumb || [],

    // 主键
    key: options.key || route.meta.key || 'id',

    // Api
    api: options.api || route.meta.api,

    // 详情
    detail: {},

    // 默认详情数据
    defaultDetail: options.defaultDetail || {},

    pageForm,

    loading: false,
  })

  const actions = {
    /**
     * 初始化
     * @param {}} options
     */
    async initData() {
      actions.getData()
    },

    /**
     * 获取数据
     */
    async getData() {
      state.loading = true

      const id = route.params.id || route.query.id

      if (id) {
        const res = await http(`${state.api}/${id}`, { showLoading: options.showLoading }).finally(() => {
          state.loading = false
        })

        if (actions.afterGetData) await actions.afterGetData(res)

        // 默认值
        Object.keys(state.defaultDetail).forEach(key => {
          if (res[key] == undefined || res[key] == null) res[key] = state.defaultDetail[key]
        })

        state.detail = res
      } else {
        state.detail = { ...state.defaultDetail }
      }
    },

    /**
     * 提交
     * @param {Boolean} goBack
     */
    handleSubmit(goBack = true) {
      pageForm.value.validate(async valid => {
        if (valid) {
          let detail = {
            ...state.detail,
          }

          const id = detail[state.key]

          // 提交成功后
          const onSuccess = res => {
            ElMessage.success(state.detail.id ? '保存成功' : '添加成功')
            if (goBack) this.handleCancel()
          }

          if (actions.handleBeforeSubmit) {
            let newData = actions.handleBeforeSubmit(detail)
            if (newData) detail = newData
            else if (newData == false) return
          }

          if (id) {
            http
              .put(`${state.api}/${id}`, detail, {
                showLoading: true,
              })
              .then(onSuccess)
          } else {
            http
              .post(`${state.api}`, detail, {
                showLoading: true,
              })
              .then(onSuccess)
          }
        }
      })
    },

    /**
     * 对于一些不需要验证的提交
     * isPost 是否是新增
     */
    handleDirectSubmit(goBack = true, isPost = false) {
      let detail = {
        ...state.detail,
      }

      const id = detail[state.key]
      // 提交成功后
      const onSuccess = res => {
        ElMessage.success(state.detail.id ? '保存成功' : '添加成功')
        if (goBack) this.handleCancel()
      }

      if (actions.handleBeforeDirectSubmit) {
        let newData = actions.handleBeforeDirectSubmit(detail)
        if (newData) detail = newData
        else if (newData == false) return
      }

      if (id && !isPost) {
        http
          .put(`${state.api}/${id}`, detail, {
            showLoading: true,
          })
          .then(onSuccess)
      } else {
        http
          .post(`${state.api}`, detail, {
            showLoading: true,
          })
          .then(onSuccess)
      }
    },

    /**
     * 取消
     */
    handleCancel() {
      router.go(-1)
    },
  }

  // 初始化
  onMounted(() => {
    actions.initData()
  })

  return {
    ...toRefs(state),
    ...actions,
    pageForm,
    pageData: state,
    pageActions: actions,
  }
}
